﻿using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Xunit;

namespace MyDemo.Serialize
{
    /// <summary>m
    /// 序列化和反序列化
    /// </summary>
    public class Class4
    {
        [Fact]
        public void Test()
        {
            MyObject obj = new MyObject(10, "我是字符串");

            Debug.WriteLine($"初始状态：{obj.ToString()}");
            //序列化对象
            byte[] data = Serialize(obj);
            //反序列化对象
            MyObject newobj = DeSerialize(data);
            Debug.WriteLine($"经过序列化和反序列化后：{newobj}");
        }

        //序列化对象
        private byte[] Serialize(MyObject obj)
        {
            IFormatter formatter = new BinaryFormatter();
            using (var ms = new MemoryStream())
            {
                formatter.Serialize(ms, obj);
                return ms.ToArray();
            }
        }

        //反序列化对象
        private MyObject DeSerialize(byte[] data)
        {
            IFormatter formatter = new BinaryFormatter();
            using (var ms = new MemoryStream(data))
            {
                return (MyObject)formatter.Deserialize(ms);
            }
        }
    }

    [Serializable]
    public class MyObject
    {
        private int _myInt;

        [NonSerialized]
        private string _myPrivate;

        public MyObject(int i, string s)
        {
            _myInt = i;
            _myPrivate = s;
        }

        public override string ToString()
        {
            return $"整数是：{_myInt},字符串是：{_myPrivate}";
        }
    }
}